package controllers

import (
	"encoding/base64"
	"fmt"
	"gin/config"
	"gin/models"
	"net/http"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

type UserController struct{}

type Base64ImageRequest struct {
	AvatarBase64 string `json:"avatarBase64" binding:"required"` // Base64 编码的图片数据
}

func (ctrl *UserController) Welcome(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"message": "Welcome to the user controller",
	})
}

func (ctrl *UserController) GetUsers(c *gin.Context) {
	var users []models.User
	config.DB.Find(&users)
	c.JSON(http.StatusOK, users)
}

func (ctrl *UserController) CreateUser(c *gin.Context) {
	var user models.User
	if err := c.ShouldBindJSON(&user); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	config.DB.Create(&user)
	c.JSON(http.StatusOK, user)
}

func (ctrl *UserController) UserLogin(c *gin.Context) {
	openID := c.GetHeader("X-WX-OPENID")

	var user models.User
	res := config.DB.Where("wx_uid = ?", openID).First(&user)
	if res.Error != nil {
		// 如果用户不存在，创建新用户
		user.WxUid = openID
	}

	if err := c.ShouldBindJSON(&user); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if res.Error != nil {

		config.DB.Create(&user)
	} else {
		config.DB.Save(&user)
	}

	c.JSON(http.StatusOK, gin.H{
		"message": "获取成功",
		"user":    user,
	})
}

func (ctrl *UserController) UploadAvatar(c *gin.Context) {
	var req Base64ImageRequest

	// 1. 绑定和验证请求数据
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求数据"})
		return
	}

	// 解析 Base64 图片数据
	fileBytes, contentType, err := decodeBase64Image(req.AvatarBase64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "图片解码失败", "details": err.Error()})
		return
	}

	// 生成唯一文件名
	filename := generateFilename(contentType)

	uploadWxaCode(fileBytes, c, filename)
}

func decodeBase64Image(data string) ([]byte, string, error) {
	// 检查并去除 data URL 前缀
	base64Data := data

	// 检测图片类型
	contentType := ""

	// 尝试从 Base64 开头推断类型
	switch {
	case strings.HasPrefix(base64Data, "/9j/"):
		contentType = "image/jpeg"
	case strings.HasPrefix(base64Data, "iV"):
		contentType = "image/png"
	case strings.HasPrefix(base64Data, "R0"):
		contentType = "image/gif"
	case strings.HasPrefix(base64Data, "Ukl"):
		contentType = "image/webp"
	default:
		return nil, "", fmt.Errorf("无法识别的图片格式:%s", base64Data)
	}

	// 解码 Base64
	decoded, err := base64.StdEncoding.DecodeString(base64Data)
	if err != nil {
		return nil, "", fmt.Errorf("base64 解码失败: %w", err)
	}

	// 验证图片完整性（可选）
	if len(decoded) == 0 {
		return nil, "", fmt.Errorf("解码后数据为空")
	}

	return decoded, contentType, nil
}

func generateFilename(contentType string) string {
	// 文件扩展名
	extension := ".jpg"
	switch contentType {
	case "image/png":
		extension = ".png"
	case "image/gif":
		extension = ".gif"
	case "image/webp":
		extension = ".webp"
	}

	// 生成唯一文件名
	return fmt.Sprintf("avatar/%d%s", time.Now().UnixNano(), extension)
}
